//
//  ShowStudentViewController.m
//  SouthChina
//
//  Created by kc on 15/7/20.
//  Copyright (c) 2015年 科创. All rights reserved.
//  我辅导的学生，界面特殊处理

#import "ShowStudentViewController.h"
#import "ShowSearchViewController.h"
#import "ContactDao.h"
#import "BDKNotifyHUD.h"
#import "ShowStudentTableViewCell.h"
#import "MessageViewController.h"
#import "selectMemberViewController.h"
#import "CreateGroupViewController.h"
#import "GroupInfoViewController.h"
#import "selectMemberTableViewCell.h"

@interface ShowStudentViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UnitViewDelegate>
{
    NSMutableArray *arrlistnj; //年级列表
    NSMutableArray *arrlistprof; //专业列表
    NSMutableArray *arrlistclass; //班级列表
    NSArray *orgContactList;
}
@property (strong, nonatomic) IBOutlet UIButton *btProf;//专业按钮
@property (strong, nonatomic) IBOutlet UIButton *btClass;//班级按钮
@property (strong, nonatomic) IBOutlet UILabel *labelroute; //路径

@property (strong, nonatomic) IBOutlet UITableView *tableview;
@property (strong, nonatomic) IBOutlet UISearchBar *searchbar;
@property (strong, nonatomic) UIButton *btGrade;

@end

@implementation ShowStudentViewController
@synthesize sref_id,curIndexnj,curIndexprof,curIndexclass,returntype,MyStudentType,selectedContact;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleBarWithBackBtn:@"" needReturn:TRUE];
    
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"ShowStudentViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.bounces=NO;
    
    _searchbar.showsCancelButton=NO;
    _searchbar.barStyle=UIBarStyleDefault;
    _searchbar.placeholder = @"请输入关键字";
    _searchbar.delegate = self;
    
    //标题栏增加 年级按钮
    _btGrade = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.origin.x+self.view.frame.size.width/2-25, self.titlebar.frame.origin.y+28, 60, 30)];
    [_btGrade addTarget:self action:@selector(ClickGradeBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_btGrade setTitle:@"2014级" forState:UIControlStateNormal];
    [self.titlebar addSubview:_btGrade];
    
    //获取搜索列表
    arrlistnj = [self GetsearchList:sref_id key:@"NJ"];
    arrlistprof = [self GetsearchList:sref_id key:@"PROF_NAME"];
    arrlistclass = [self GetsearchList:sref_id key:@"CLASS_NAME"];
    curIndexnj = -1;
    curIndexprof = -1;
    curIndexclass = -1;
    _oldselectnj = @"";
    _oldselectprof = @"";
    
    //初始化时，不按任何条件搜索
    orgContactList = [ContactDao searcherNodeContact:sref_id key:@""];
    [self ShowSearchRoute];
                                               
                                         
   // myLable1.font = [UIFont fontWithName:@"Thonburi-Bold" size:14.0f];
    //显示与选择我辅导的学生界面不同
    _selectedmeberlist.isDoneButton = YES;
    _selectedmeberlist = [_selectedmeberlist initWithFrame:_selectedmeberlist.frame];
    _selectedmeberlist.delegate = self;
    
    if([MyStudentType isEqualToString:SHOW_MYSTUDENT])
    {
        _selectedmeberlist.hidden = YES;
        _tbviewBtmconstrait.constant = 0;
    }
    else {
        _selectedmeberlist.hidden = NO;
        _tbviewBtmconstrait.constant = 50;
    }
    
    NSLog(@"******%ld",orgContactList.count);
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    NSLog(@"搜索列表");
    [self resortContactList:searchText];
    [_tableview reloadData];
    
}

-(void)resortContactList:(NSString *)searchKey
{
    //根据名称修改
    orgContactList = [ContactDao searcherNodeContact:sref_id key:searchKey];
}

-(void)ShowSearchRoute
{
    //搜索路径：我的辅导学生-2014级
    UILabel * routeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,2.0,300,13)];
    routeLabel.textAlignment = NSTextAlignmentLeft;
    routeLabel.font = [UIFont systemFontOfSize:12.0f];
    routeLabel.textColor = [UIColor grayColor];
    NSString *sRoute = [[NSString alloc]init];
    //默认
    sRoute = @"我辅导的学生";
   
    if(curIndexnj!=-1)
        sRoute = [sRoute  stringByAppendingString:[NSString stringWithFormat:@">%@",arrlistnj[curIndexnj]]];
    if(curIndexprof!=-1)
        sRoute = [sRoute  stringByAppendingString:[NSString stringWithFormat:@">%@",arrlistprof[curIndexprof]]];
    if(curIndexclass!=-1)
        sRoute = [sRoute  stringByAppendingString:[NSString stringWithFormat:@">%@",arrlistclass[curIndexclass]]];
    routeLabel.text = sRoute;
    [_labelroute addSubview:routeLabel];
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return orgContactList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([MyStudentType isEqualToString:SHOW_MYSTUDENT])
    {
        static NSString * CellIdentifier = @"ShowStudentTableViewCell";
        ShowStudentTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        }
        Contact *contact = orgContactList[indexPath.row];
        //名称
        cell.username.text = contact.mNAME;
        cell.username.font = [UIFont boldSystemFontOfSize:13];
        //头像
        NSURL *url = [NSURL URLWithString: contact.mHEAD_IMG];
        [cell.userimage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        
        return cell;
    }
    else{
        static NSString * CellIdentifier = @"selectMemberTableViewCell";
        selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(!cell)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        }
        Contact *contact = orgContactList[indexPath.row];
        
        [cell setContactSelected:[self containsContact:selectedContact contact:contact]];
        [cell setSelectMemberTableViewCell:contact];
        
        return cell;
    }
    return nil;
}




- (BOOL)containsContact:(NSMutableSet*) set contact:(Contact *)contact
{
    for (Contact * i   in  set)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            return YES;
        }
    }
    return NO;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选中某行
    NSLog(@"cell*******");
    Contact *contact = orgContactList[indexPath.row];
    if ([MyStudentType isEqualToString:SHOW_MYSTUDENT]) {
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"2",@"record_DB_ID":contact.mPK_ID,
                               @"recordID":contact.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
    }
    else{
        BOOL isFind = NO;
        for (Contact * i   in  selectedContact)
        {
            if ([i.mID isEqualToString:contact.mID]) {
                [selectedContact removeObject:i];
                [_selectedmeberlist removeUnit:contact];
                isFind = YES;
                break;
            }
        }
        
        if (!isFind) {
            [selectedContact addObject:contact];
            [_selectedmeberlist addNewUnit:contact];
        }
        
        
        NSArray *indexArray=[NSArray arrayWithObject:indexPath];
        [_tableview reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// NSArray * orgContactList = [ContactDao searcherNodeContact:curOrgContact.mID key:key];

-(NSMutableArray*)GetsearchList:(NSString*)ref_id key:(NSString*)key{
    NSMutableArray *returnlist = [[NSMutableArray alloc] init];
   //获取列表
   NSString * where = [NSString stringWithFormat:@"where ref_id='%@' ",ref_id];
  returnlist =  [ContactDao queryOrgWithrefidandkey:key ConditionSQL:where];
   return returnlist;
}

//点击年级：年级列表不变化
-(void)ClickGradeBtn:(id)sender
{
    ShowSearchViewController * showSearch = [[ShowSearchViewController alloc] init];
    showSearch.searchkey = @"NJ";
    showSearch.curIndex = curIndexnj;
    showSearch.arrsearchlist = arrlistnj;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:showSearch animated:NO];
    
}

//点击专业：根据年级筛选
- (IBAction)btClickProf:(id)sender {
    
    NSString *wheresearch = [NSString stringWithFormat:@"where ref_id='%@'",sref_id];
    if(curIndexnj>=0)
    {
        NSString *wheretmp = [NSString stringWithFormat:@"and nj='%@'",[arrlistnj objectAtIndex:curIndexnj]];
        wheresearch = [wheresearch stringByAppendingString:wheretmp];
    }
    arrlistprof =  [ContactDao queryOrgWithrefidandkey:@"PROF_NAME" ConditionSQL:wheresearch];
    ShowSearchViewController * showSearch = [[ShowSearchViewController alloc] init];
    showSearch.searchkey = @"PROF_NAME";
   
    if(curIndexnj>=0)
    {
        if(![_oldselectnj isEqualToString:[arrlistnj objectAtIndex:curIndexnj]])
        {
            curIndexprof = -1;
            _oldselectnj = [arrlistnj objectAtIndex:curIndexnj];
        }
    }
    showSearch.curIndex = curIndexprof;
    showSearch.arrsearchlist = arrlistprof;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:showSearch animated:NO];
}

//点击班级：根据专业和年级筛选
- (IBAction)btClickClass:(id)sender {
   //需要先选择了专业，才可以选择班级
    NSLog(@"年级：%lu.........专业：%lu",curIndexnj,curIndexprof);
   if(arrlistprof.count>0 && curIndexprof==-1)
   {
       //提示要选择专业
       [MBProgressHUD hideHUDForView:self.view animated:YES];
       [self showAlerHUD:@"请先选择专业"];
       return;
   }
   
    NSString *wheresearch = [NSString stringWithFormat:@"where ref_id='%@' and prof_name='%@'",sref_id,[arrlistprof objectAtIndex:curIndexprof]];
   
    if(curIndexnj>=0)
    {
        NSString *wheretmp = [NSString stringWithFormat:@"and nj='%@'",[arrlistnj objectAtIndex:curIndexnj]];
        wheresearch = [wheresearch stringByAppendingString:wheretmp];
    }
    
    arrlistclass =  [ContactDao queryOrgWithrefidandkey:@"CLASS_NAME" ConditionSQL:wheresearch];
       
   ShowSearchViewController * showSearch = [[ShowSearchViewController alloc] init];
   showSearch.searchkey = @"CLASS_NAME";
    if(![_oldselectprof isEqualToString:[arrlistprof objectAtIndex:curIndexprof]])
    {
        _oldselectprof = [NSString stringWithFormat:@"%@",[arrlistprof objectAtIndex:curIndexprof]];
        curIndexclass = -1;
    }
    NSLog(@"之前的专业：%@",_oldselectprof);
    NSLog(@"当前专业：%@",[arrlistprof objectAtIndex:curIndexprof]);
    showSearch.curIndex = curIndexclass;
    showSearch.arrsearchlist = arrlistclass;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:showSearch animated:NO];
}

//重写提示效果
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImage:[UIImage imageNamed:@"icon_warning"]  text:text];
    hudex.center = CGPointMake(self.view.center.x, _btClass.frame.origin.y+150);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}



//刷新
-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"专业index:%lu,班级index:%lu",curIndexprof,curIndexclass);
    //更改按钮上的文字
    if(curIndexnj>=0  && curIndexnj<arrlistnj.count)
        [_btGrade setTitle:[arrlistnj objectAtIndex:curIndexnj] forState:UIControlStateNormal];
    
    if(curIndexprof>=0 && curIndexprof<arrlistprof.count)
        [_btProf setTitle:[arrlistprof objectAtIndex:curIndexprof] forState:UIControlStateNormal];
    
    if(curIndexclass>=0 && curIndexclass<arrlistclass.count)
        [_btClass setTitle:[arrlistclass objectAtIndex:curIndexclass] forState:UIControlStateNormal];
   
    
    NSString *wheretable = [NSString stringWithFormat:@"where ref_id='%@' and operate='U'",sref_id];
    
    if(curIndexnj>=0)
    {
        NSString *wheretmp = [NSString stringWithFormat:@"and nj='%@'",[arrlistnj objectAtIndex:curIndexnj]];
        wheretable = [wheretable stringByAppendingString:wheretmp];
    }
    
    if(curIndexprof>=0)
    {
        NSString *wheretmp = [NSString stringWithFormat:@"and prof_name='%@'",[arrlistprof objectAtIndex:curIndexprof]];
        wheretable = [wheretable stringByAppendingString:wheretmp];
    }
    
    if(curIndexclass>=0)
    {
        NSString *wheretmp = [NSString stringWithFormat:@"and class_name='%@'",[arrlistclass objectAtIndex:curIndexclass]];
        wheretable = [wheretable stringByAppendingString:wheretmp];
    }
    //刷新表数据
    orgContactList  = [ContactDao getContactByWhere:wheretable];
    NSLog(@"学生个数：%lu",orgContactList.count);
    [_tableview reloadData];
    [self ShowSearchRoute];
    
    //刷新选择列表
    [_selectedmeberlist removeAll];
    for( Contact * contact in selectedContact)
    {
        [_selectedmeberlist addNewUnit:contact];
    }
}

- (void) extendCellTouched:(UnitCell *)unitCell
{
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    
    for (Contact * i   in  selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [selectedContact removeObject:i];
            break;
        }
    }
}


- (void) unitDoneTouched:(id)sender
{
    if([_CreateType isEqualToString:CREATETYPE_CREATEGROUP])
    {
        NSLog(@"点击选择成员完成");
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[CreateGroupViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }
    else if([_CreateType isEqualToString:CREATETYPE_ADDGROUP])
    {
        //添加群成员
        NSLog(@"添加群成员"); //GroupInfoViewController
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[GroupInfoViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }
    else if([_CreateType isEqualToString:CREATETYPE_CREATECHAT])
    {
        //创建讨论组
        if(selectedContact.count >200 || selectedContact.count <2)
        {
            [self showAlerHUD:@"添加的成员人数不能小于2人和大于200人"];
            return;
        }
        
        /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
         "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
         "groupName":"信网中心群",--群名称 选填
         "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
         "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
        NSEnumerator *enumerator = [selectedContact objectEnumerator];
        NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
        [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
        for (Contact *cid in enumerator) {
            [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        }
        
        NSDictionary *dict  = @{@"groupType":@"3",
                                @"userIds":ids,
                                @"groupName":@"",
                                @"groupTags":@"",
                                @"toMountGroupId":@""};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                            [view show];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"创建讨论组失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"创建讨论组失败！"];
                        
                    }
                    
                }];
                
            }else{
                UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
                [view show];
            }
            
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        kAppDelegate.needRefrsh = YES;
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}


@end
